/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
 
import md5 from '@/node_modules/js-md5/src/md5.js';
const yiyu = {
	//接口地址
	interfaceUrl: function() {
		return yiyu.getUrl()+'api/'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? '123' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
		const model = res.model.replace(/\s/g, "").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	/* 搜索词写入缓存 */
	setKeywords(data){
		uni.setStorageSync("yyui_key_words", data)
	},
	getKeywords(){
		return uni.getStorageSync("yyui_key_words")
	},
	/* 缓存默认地址 */
	setAddressId(data){
		uni.setStorageSync("yyui_key_address", data)
	},
	getAddressId(){
		return uni.getStorageSync("yyui_key_address")
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading,action) {
		//接口请求
		let loadding = false;
		yiyu.delayed && uni.hideLoading();
		clearTimeout(yiyu.delayed);
		yiyu.delayed = null;
		if (!hideLoading) {
			yiyu.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		/* 公共参数 */
        postData.time_stamp = yiyu.timest();
        postData.method = action;
		let keys=yiyu.getToken()?yiyu.getKey():action;
		if(action=='checkOrderPay' || action=='wxPubAuth'){
			keys=action;
		}
        postData.sign = yiyu.getSign(postData,keys);
		return new Promise((resolve, reject) => {
			uni.request({
				url: yiyu.interfaceUrl() + url,
				data: postData,
				header: {
					'content-type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
					'token': yiyu.getToken(),
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(yiyu.delayed)
					yiyu.delayed = null;
					/* 检测是否是分享的拼团信息传递 */
					// #ifdef H5
					  this.getUrlParams();
					// #endif
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if(res.data.code==40001 || res.data.code==10014 || res.data.code==10010){
						yiyu.logout();
						// let ua = window.navigator.userAgent.toLowerCase()
						// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
						// 	this.hasAutoLogin();
						// 	return;
						// }
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
					/* 登录信息 */
					
				    if (res.data.code == 40163 || res.data.code==40029) {
				    	this.getCode();
				    	return;
				    }
					if(res.data.code == 200 && res.data.data){
						if(res.data.data.token){
							
							yiyu.setUserInfo(postData.mobile,res.data.data.token,res.data.data.api_key);
			               if(yiyu.getShopId()){
			               	uni.navigateTo({
			               		// url: '/pageschild/shop/offlinePay?shop_id='+yiyu.getShopId()
			               	})
			               	return;
			               }
							uni.switchTab({
								url: '/pages/index/index'
							})
							return;
						}
					}
					// if(res.data.code!=200){
					// 	this.toast(res.data.message);
					// 	//判断是否token 过期
					// }
					resolve(res.data);
				},
				fail: (res) => {
					clearTimeout(yiyu.delayed)
					yiyu.delayed = null;
					yiyu.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	mrequest: function(url, method, postData, isDelay, isForm, hideLoading,action,mch_key) {
		//接口请求
		let loadding = false;
		yiyu.delayed && uni.hideLoading();
		clearTimeout(yiyu.delayed);
		yiyu.delayed = null;
		if (!hideLoading) {
			yiyu.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		/* 公共参数 */
	    postData.time_stamp = yiyu.timest();
	    postData.method = action;
		let keys=yiyu.getToken()?yiyu.getKey():action;
		if(action=='checkOrderPay' || action=='wxPubAuth'){
			keys=action;
		}
	    postData.sign = yiyu.getSign(postData,keys);
		return new Promise((resolve, reject) => {
			uni.request({
				url: yiyu.interfaceUrl() + url,
				data: postData,
				header: {
					'content-type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
					'token': yiyu.getToken(),
					// 'mch-key':mch_key
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(yiyu.delayed)
					yiyu.delayed = null;
					
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					
					if(res.data.code == 200 && res.data.data){
						
					}
					resolve(res.data);
					return;
				},
				fail: (res) => {
					clearTimeout(yiyu.delayed)
					yiyu.delayed = null;
					yiyu.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, postData, files,action) {
		uni.showLoading({
			title: '请稍候...'
		})
		
		postData.time_stamp = yiyu.timest();
		let keys=yiyu.getToken()?yiyu.getKey():action;
		// console.log(postData);return;
		postData.sign = yiyu.getSign(postData,yiyu.getKey());
		postData.method = action;
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: yiyu.interfaceUrl() + url,
			    filePath: files,
				name: 'imageFile',
				header: {
					'token': yiyu.getToken()
				},
				formData:postData,
				success: function(res) {
					uni.hideLoading()
					res.data=JSON.parse(res.data)
					resolve(res.data);
				},
				fail: function(res) {
					reject(res)
					this.toast(res.msg);
				}
			})
		})
	},
	/**
	 * 上传视频
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadVedio: function(url, postData, files,action) {
		uni.showLoading({
			title: '请稍候...'
		})
		
		postData.time_stamp = yiyu.timest();
		let keys=yiyu.getToken()?yiyu.getKey():action;
		// console.log(postData);return;
		postData.sign = yiyu.getSign(postData,yiyu.getKey());
		postData.method = action;
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: yiyu.interfaceUrl() + url,
			    filePath: files,
				name: 'videoFile',
				header: {
					'token': yiyu.getToken()
				},
				formData:postData,
				success: function(res) {
					uni.hideLoading()
					res.data=JSON.parse(res.data)
					resolve(res.data);
				},
				fail: function(res) {
					reject(res)
					this.toast(res.msg);
				}
			})
		})
	},
	yiyuJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let yiyuScript = document.createElement("script");
		yiyuScript.src = url;
		yiyuScript.type = "text/javascript";
		document.head.appendChild(yiyuScript);
		document.head.removeChild(yiyuScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile, token,key) {
		uni.setStorageSync("yyui_token", token)
		uni.setStorageSync("yyui_key", key)
		uni.setStorageSync("yyui_mobile", mobile)
	},
	//设置用户信息
	setUserInfoData:function(data){
		uni.setStorageSync("yyui_user_data", data)
	},
	getUserInfoData:function(){
		return uni.getStorageSync("yyui_user_data")
	},
	setUserSign:function(data){
		uni.setStorageSync("yyui_user_sign", data)
	},
	getUserSign:function(){
		return uni.getStorageSync("yyui_user_sign")
	},
	getWxAuto:function(){
		return uni.getStorageSync("yyui_wx_data")
	},
	setUserRefereeData:function(shareid){
		uni.setStorageSync("yyui_shareid", shareid)
	},
	getUserReferee:function(){
		return uni.getStorageSync("yyui_shareid")
	},
	setShopData:function(data){
		uni.setStorageSync("yyui_shop_data", data)
	},
	getShopData:function(){
		return uni.getStorageSync("yyui_shop_data")
	},
	getShopId:function(){
		return uni.getStorageSync("yyui_shop_id")
	},
	//写入用户小程序头像信息
	setWxAuto(data){
		uni.setStorageSync("yyui_wx_data", data)
	},
	getWxAutophone:function(){
		return uni.getStorageSync("yyui_wx_data_phone")
	},
	getWxOpenId: function() { //获取微信openid
		return uni.getStorageSync("wx_openid");
	},
	setWxOpenId: function($openId) { //设置微信openid
		uni.setStorageSync("wx_openid", $openId);
	},
	//微信授权获取用户openid
	getWxOauthOpenId() {
		let openId = this.getWxOpenId();
		if (openId != '') return true;
		uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					/* 公共参数 */
					let datas={};
					console.log(loginRes)
					datas.code=loginRes.code
					let results=yiyu.request('login', 'post', datas, 1000, 1, '', 'checkWechatUser');
					Promise.resolve(results).then((value) => {
						
						if (value.code == 200) {
							yiyu.setWxOpenId(value.data.openid);
						} 
					})
					return
				}
		});
		
	},
	/* 二维码缓存信息 */
	setImgs(data){
		uni.setStorageSync("yyui_imgs", data)
	},
	/* 用户缓存是否从拼团分享过来的信息 */
	setSharePintuan(data){
		uni.setStorageSync("yyui_pintuan", data)
	},
	getSharePintuan(){
	
		return uni.getStorageSync("yyui_pintuan")
	},
	getImgs(){
		return uni.getStorageSync("yyui_imgs")
	},
	//写入用户小程序手机号码信息
	setWxAutophone(data){
		uni.setStorageSync("yyui_wx_data_phone", data)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("yyui_token")
	},
	getUrl(){
		let baseUlr='http://www.zjsht.cn/'
		return baseUlr;
	},
	getAppid(){
		let appid='wx5d6f5358f25ffac8'
		return appid;
	},
	setWechatJson(data){
		uni.setStorageSync("yyui_wechat_data", data)
	},
	getWechatJson(){
		return uni.getStorageSync("yyui_wechat_data")
	},
	setReferee(data){
		uni.setStorageSync("yyui_referee_data", data)
	},
	getReferee() {
		return uni.getStorageSync("yyui_referee_data")
	},
	//获取key
	getKey(){
		return uni.getStorageSync("yyui_key")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("yyui_token") ? true : false
	},
	//跳转登录页面
	haslogin: function(shareid){
		
		   if (yiyu.getToken()) {
			return;
		   }
		  // #ifdef MP-WEIXIN
		  if (yiyu.getToken()) {
		  	return;
		  }
		  if (shareid) {
		  	uni.navigateTo({
		  		url: '/pages/login/wxauthLogin?shareCode=' + shareid
		  	})
		  	return;
		  } else {
		  	uni.navigateTo({
		  		url: '/pages/login/wxauthLogin'
		  	})
		  	return;
		  }
		  // #endif
		   // #ifdef H5
		   this.getUrlParams();
		    // let ua = window.navigator.userAgent.toLowerCase()
		  //  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			 //   /* 假如未授权登陆的时候*/
		  //  		let res = this.getUrlCode();
		  //  		if (!res.code) {
		  //  			this.getCode();
		  //  		} else {
		  //  		let datas={
		  //  			code: res.code,
		  //  		};
				// if(yiyu.getToken()){
				// 	return;
				// }
		  //  		let result=this.request('login','post',datas,1000,1,'','wxPubAuth');
		  //  			Promise.resolve(result).then((value)=>{
				
		  //  			    if(value.code==200){
		  //  					this.setUserInfo(value.data.mobile,value.data.token,value.data.api_key);
				// 		}else{
				// 			if(value.code==10178){
				// 				/* 跳转到授权页面 */
				// 				uni.navigateTo({
				// 					url: '/pages/login/authLogin'
				// 				})
				// 			}
				// 		}
		  //  			})		
		  //  		}
				// return;
		  //   }
			 // #endif
		if(yiyu.isLogin()===false){
			if(shareid){
				return;
			}
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
	},
	//跳转登录页面
	authlogin: function(){
		   if (yiyu.getToken()) {
			  return true;
		   }
		  // #ifdef MP-WEIXIN
		   uni.navigateTo({
		 	 url: '/pages/login/wxauthLogin'
		   })
		  // #endif
		   // #ifdef H5
		   this.getUrlParams();
		  //   let ua = window.navigator.userAgent.toLowerCase()
		  //  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			 //   /* 假如未授权登陆的时候*/
		  //  		let res = this.getUrlCode();
		  //  		if (!res.code) {
		  //  			this.getCode();
		  //  		} else {
		  //  		let datas={
		  //  			code: res.code,
		  //  		};
		  //  		let result=this.request('login','post',datas,1000,1,'','wxPubAuth');
		  //  			Promise.resolve(result).then((value)=>{
		  //  			    if(value.code==200){
		  //  					this.setUserInfo(value.data.mobile,value.data.token,value.data.api_key);
				// 		}else{
				// 			if(value.code==10178){
				// 				/* 跳转到授权页面 */
				// 				uni.navigateTo({
				// 					url: '/pages/login/reg/reg'
				// 				})
				// 			}
				// 		}
		  //  			})		
		  //  		}
				// return true;
		  //   }
			 // #endif
			uni.navigateTo({
				url: '/pages/login/reg/reg'
			})
	},
	//是否跳转到微信授权页面
	hasAutoLogin: function(referee_id){
		// let ua = window.navigator.userAgent.toLowerCase()
		// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		// 	    this.hrefTo();
		// 	     //判断是否是已经授权用户信息过的
		// 		// let res = this.getUrlCode();
		// 		 this.setReferee(referee_id);
		// 		// if (!res.code) {
		// 		// 	this.getCode();
		// 		// }
		//  }
	},
	
	/* 拉起授权 */
	getOauth2:function(){
		this.getCode();
	},
	//退出登录
	logout:function(){
		uni.setStorageSync("yyui_token",'')
		uni.setStorageSync("yyui_key",'')
		uni.setStorageSync("yyui_mobile", '')
		uni.setStorageSync("yyui_user_data",'')
		uni.setStorageSync("yyui_shop_data",'')
		uni.setStorageSync("yyui_pintuan", '')	
	},
	//跳转个人中心
    hrefTo(){
	
		if(yiyu.getToken()){
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
		
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !yiyu.isLogin()) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},

	//*再次授权获取信息 */
	getCode() {
		this.code = ''
		let shareCode = this.getUserReferee();
		if(shareCode){
			var local = yiyu.getUrl()+'index.html#/pages/login/reg/reg?shareCode='+shareCode+"&code="+this.code // 获取页面u
		}else{
			var local =yiyu.getUrl()+'index.html#/pages/index/index' // 获取页面
		}
		var appid = yiyu.getAppid()
		window.location.href =
			  `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
	},
	getUrlCode() { // 截取url中的code方法
		var url = location.search
		this.winUrl = url
		var theRequest = new Object()
		if (url.indexOf("?") != -1) {
			var str = url.substr(1)
			var strs = str.split("&")
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
			}
		}
		return theRequest
	},
	getUrlParams(){
		var url = location.href
		var theRequest = new Object()
		let datas={};
		if (url.indexOf("tuanDetail?") != -1) {
			var str = url.substr(1)
			var strs = str.split("tuanDetail?")
			var strs = strs[1].split("&")
			datas.group_id=strs[0].substr(9);
			datas.sku_id=strs[1].substr(7);
		    this.setSharePintuan(datas)
		}
	},
	timest: function() {
	        var tmp = Date.parse(new Date()).toString();
	        tmp = tmp.substr(0, 10);
	        return tmp;
	},
	
	getSign: function(params,kAppSecret) {
		
			
		
		
	        if (typeof params == "string") {
	            return yiyu.paramsStrSort(params,kAppSecret);
	        } else if (typeof params == "object") {
	            var arr = [];
	            for (var i in params) {
					if(i!='sign'){
						if(params[i]!=''){
							arr.push((i + "=" + params[i]));
						}
					
					}
	            }
				
	            return yiyu.paramsStrSort(arr.join(("&")),kAppSecret);
	        }
	    },
	/* 微信分享 */
	share: function(url, data, token) {
		var jweixin = require('jweixin-module');
		var surl = encodeURIComponent(url);
		console.log(surl);
		let obj = {
			token: token,
			url: surl,
		}
		let orders = this.request('user', 'post', obj, 1000, 1, '', 'wxShare');
		Promise.resolve(orders).then((value) => {
			if (value.code == 10000) {
				jweixin.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。  
					appId: value.data.appId, // 必填，公众号的唯一标识  
					timestamp: value.data.timestamp, // 必填，生成签名的时间戳  
					nonceStr: value.data.nonceStr, // 必填，生成签名的随机串  
					signature: value.data.signature, // 必填，签名，见附录1  
					surl: value.data.url, //自己添加的，debug为true的时候可以网页打印出对应的URL是否正确  
					jsApiList: ["onMenuShareAppMessage", "onMenuShareTimeline"],
				});
				jweixin.ready(function() {
					//自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）  
					jweixin.onMenuShareAppMessage({
						title: data.title, // 分享标题
						desc: data.desc, // 分享描述
						link: data.url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						imgUrl: data.pic, // 分享图标
						type: '', // 分享类型,music、video或link，不填默认为link
						dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空                             
						success: function() {
							// 用户确认分享后执行的回调函数  
						},
					});
					//自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）  
					jweixin.onMenuShareTimeline({
						title: data.title, // 分享标题                                  
						link: data.url, // 分享链接  
						imgUrl: data.pic, // 分享图标                                
						success: function() {
							// 用户确认分享后执行的回调函数  
						},
					});
				});
			} else {
				this.showToast(value.message)
			}
		})
	},
	paramsStrSort: function(paramsStr, kAppSecret) {
			
	        var str = paramsStr.split("&").sort().join("&");
	        var sign = md5(str + kAppSecret);
	        return sign.toUpperCase();
	    }
}

export default yiyu
